package com.taotao.tools.springmvc.xss.jackson;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.ContextualSerializer;
import com.taotao.tools.enums.annotation.EnumField;
import com.taotao.tools.enums.jackson.EnumAtSerializer;
import org.apache.commons.text.StringEscapeUtils;

import java.io.IOException;


/**
 * 处理向前端发送的JSON数据，将数据进行转译后发送
 */
public class XssJacksonSerializer extends JsonSerializer<String> implements ContextualSerializer {
    @Override
    public void serialize(String value, JsonGenerator jgen, SerializerProvider provider) throws IOException {
        jgen.writeString(StringEscapeUtils.escapeHtml4(value));
    }


    @Override
    public JsonSerializer<?> createContextual(SerializerProvider serializerProvider, BeanProperty beanProperty) throws JsonMappingException {
        if (beanProperty == null) {
            //为空直接跳过
            return serializerProvider.findNullValueSerializer(beanProperty);
        }


        EnumField enumAt = beanProperty.getAnnotation(EnumField.class);
        if (null == enumAt) {
            return serializerProvider.findValueSerializer(beanProperty.getType(), beanProperty);
        }

        return new EnumAtSerializer(beanProperty.getName(), beanProperty.getType().getRawClass(), enumAt);
    }
}